package tk.cful.servlets;

import tk.cful.core.DBManager;
import tk.cful.ejb.UserManagerLocal;
import tk.cful.utils.DigestHelper;

import javax.ejb.EJB;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * UserEntity: Root
 * Date: 08.11.13
 * Time: 14:35
 */
@WebServlet(name = "SecurityCheckServlet", urlPatterns = {"/security_check"})
public class SecurityCheckServlet extends HttpServlet {

    @EJB
    private UserManagerLocal userManager;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String operation = request.getParameter("op");
        if (operation == null) {
            checkIfLoggedIn(request, response);
        } else if (operation.equals("login")) {
            logIn(request, response);
        } else if (operation.equals("register")) {
            register(request, response);
        } else if (operation.equals("logout")) {
            logOut(request, response);
        }
    }

    private void register(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        try {
            String login = request.getParameter("login");
            String password = request.getParameter("password");
            String confirm = request.getParameter("confirm");
            if (login == null || login.equals(""))
                throw new ServletException("User name is required");
            if (password == null || password.equals(""))
                throw new ServletException("Password is required");
            if (!confirm.equals(password))
                throw new ServletException("Password is not confirmed");

            if (DBManager.getInstance().findUserByName(login) != null)
                throw new ServletException("Login already used");

            if (userManager.register(login, DigestHelper.getInstance().sha256Hash(password, login))) {
                HttpSession session = request.getSession(true);
                session.setAttribute("user_name", login);

                String rootPath = System.getProperty("catalina.home");
                ServletContext ctx = request.getServletContext();
                String relativePath = ctx.getInitParameter("tempfile.dir");
                File file = new File(rootPath + File.separator + relativePath + File.separator + login);
                if (!file.exists()) file.mkdirs();

                response.sendRedirect("/cful/workspace");
            } else response.sendRedirect("/cful/reg.html");
        } catch (Exception e) {
            response.sendRedirect("/cful/reg.html#error:" + e.getMessage());
        }
    }

    private void checkIfLoggedIn(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String page = request.getParameter("page");
        HttpSession session = request.getSession(true);
        String userName = (String) session.getAttribute("user_name");
        if (userName != null && !userName.equals("")) {
            if (page != null && !page.equals(""))
                response.sendRedirect(page);
            else response.sendRedirect("/cful/workspace");
        } else
            response.sendRedirect("/cful/index.html");
    }

    private void logIn(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String login = request.getParameter("login");
        String password = request.getParameter("password");
        if (userManager.login(login, DigestHelper.getInstance().sha256Hash(password, login))) {
            HttpSession session = request.getSession(true);
            session.setAttribute("user_name", login);
            response.sendRedirect("/cful/workspace");
        } else response.sendRedirect("/cful/login.html");
    }

    private void logOut(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        HttpSession session = request.getSession(true);
        session.removeAttribute("user_name");
        response.sendRedirect("/cful/index.html");
    }
}
